#include "PageCache.h"
#include "Common.h"

PageCache PageCache::_sInst;// 饿汉模式，类加载时就创建instance对象
//PageCache PageCache::_sInst;

Span* PageCache::NewSpan(size_t k)
{
	assert(k > 0 && k < NPAGES);

	if (!_spanLists[k].Empty())
	{
		return _spanLists[k].PopFront();
	}
	for (int i = 1; i < NPAGES; i++)
	{
		if (!_spanLists[i].Empty())
		{
			// 将这个Span切分k和n-k页
			Span* nSpan = _spanLists[i].PopFront();
			Span* kSpan = new Span;
			//kSpan->_freeList = nSpan->_freeList;// 本层只初始化_pageId和_n, 此时不初始化_freeList,留到下一层初始化
			kSpan->_n = k;
			kSpan->_pageId = nSpan->_pageId;
			nSpan->_n -= k;
			nSpan->_pageId += k;

			_spanLists[nSpan->_n].PushFront(nSpan);
			return kSpan;
		}
	}

	void* ptr = SystemAlloc(NPAGES - 1);
	Span* bigSpan = new Span;
	bigSpan->_pageId = (PAGE_ID)ptr >> PAGE_SHIFT;
	bigSpan->_n = NPAGES - 1;
	_spanLists[bigSpan->_n].PushFront(bigSpan);
	return NewSpan(k);
}

